import { Collection } from "mongodb";
import { DBclient } from "../utils/db";
import { Random } from "../utils/random";
const db = new DBclient();

export class Role extends Random {
  coll: Promise<Collection<any>> | any
  async getcoll() {
    if (!this.coll) {
      this.coll = db.getCollection('role')
    }
    return this.coll;
  }
  /**
   * 查询符合条件的数据总数
   * @param query 查询条件
   * @returns 总条数
   */
  async count(query = {}): Promise<number> {
    const coll = await this.getcoll();
    const data = await coll.countDocuments(query);
    return data
  }

  /**
   * 根据条件获取数据
   * @param body 查询条件
   * @returns 查询结果
   */
  async query(body: object | any) {
    let { page: { size, page }, query = {} } = body;
    const coll = await this.getcoll();
    console.log(coll, page);

    const data = await coll.find(query).skip(--page * size).limit(size - 0).toArray();
    const total = await this.count(query);
    return { page: ++page, size: size - 0, total, data }
  }
  /**
   * 添加数据
   * @param params 传入参数
   * @returns 添加状态
   */
  async add(params: object | any) {
    const coll = await this.getcoll();
    params.id = await this.ID(coll);
    const { result } = await coll.insertOne(params);
    return result;
  }

  /**
   * 更新数据
   * @param params 更新数据
   * @returns 更新状态
   */
  async edit(params: object | any) {
    const coll = await this.getcoll();
    const { id, ...items } = params;
    const { result } = await coll.updateOne({ id }, { $set: items });
    return result;
  }
  /**
   * 删除数据
   * @param id 数据id
   * @returns 删除状态
   */
  async del(id: number) {
    const coll = await this.getcoll();
    const { result } = await coll.deleteOne({ id })
    return result
  }
}
